<?php
GLOBAL $m, $a, $project_id, $f, $min_view, $query_string, $durnTypes;
GLOBAL $task_sort_item1, $task_sort_type1, $task_sort_order1;
GLOBAL $task_sort_item2, $task_sort_type2, $task_sort_order2;
GLOBAL $user_id, $dPconfig;
/*
 tasks.php

 This file contains common task list rendering code used by
 modules/tasks/index.php and modules/projects/vw_tasks.php

 in

 External used variables:

 * $min_view: hide some elements when active (used in the vw_tasks.php)
 * $project_id
 * $f
 * $query_string
 */

if (empty($query_string)) {
	$query_string = "?m=$m&a=$a";
}

global $tasks_opened;
global $tasks_closed;

$tasks_closed = array();
$tasks_opened = $AppUI->getState('tasks_opened');
if(!$tasks_opened){
	$tasks_opened = array();
}

$task_id = intval( dPgetParam( $_GET, 'task_id', 0 ) );
$pinned_only = intval( dPgetParam( $_GET, 'pinned', 0) );
if($task_id > 0){
	$_GET['open_task_id'] = $task_id;
}

if(($open_task_id = dPGetParam($_GET, 'open_task_id', 0)) > 0 && !in_array($_GET['open_task_id'], $tasks_opened)) {
	$tasks_opened[] = $_GET['open_task_id'];
}

// Closing tasks needs also to be within tasks iteration in order to
// close down all child tasks
if(($close_task_id = dPGetParam($_GET, 'close_task_id', 0)) > 0) {
	closeOpenedTask($close_task_id);
}

// Close all tasks at once
if(dPGetParam($_GET, 'close_task_all', 0) > 0) {
	foreach ($tasks_opened as $to)
		closeOpenedTask($to);
}

// shall all tasks be opened?
$open_task_all = dPGetParam($_GET, 'open_task_all', 0);

$durnTypes = dPgetSysVal( 'TaskDurationType' );
$taskPriority = dPgetSysVal( 'TaskPriority' );

$task_project = intval( dPgetParam( $_GET, 'task_project', null ) );

$task_sort_item1 = dPgetParam( $_GET, 'task_sort_item1', '' );
$task_sort_type1 = dPgetParam( $_GET, 'task_sort_type1', '' );
$task_sort_item2 = dPgetParam( $_GET, 'task_sort_item2', '' );
$task_sort_type2 = dPgetParam( $_GET, 'task_sort_type2', '' );
$task_sort_order1 = intval( dPgetParam( $_GET, 'task_sort_order1', 0 ) );
$task_sort_order2 = intval( dPgetParam( $_GET, 'task_sort_order2', 0 ) );
if (isset($_POST['show_task_options'])) {
	$AppUI->setState('TaskListShowIncomplete', dPgetParam($_POST, 'show_incomplete', 0));
}
$showIncomplete = $AppUI->getState('TaskListShowIncomplete', 0);

require_once $AppUI->getModuleClass('projects');
$project =& new CProject;
$allowedProjects = $project->getAllowedSQL($AppUI->user_id);

if ( count($allowedProjects)) {
	$where_list = implode(' AND ', $allowedProjects);
}

$working_hours = ($dPconfig['daily_working_hours']?$dPconfig['daily_working_hours']:8);

$q = new DBQuery;
$q->addTable('projects');
$q->addQuery('company_name, project_id, project_color_identifier, project_name,'
	.' SUM(t1.task_duration * t1.task_percent_complete'
	.' * IF(t1.task_duration_type = 24, '.$working_hours.', t1.task_duration_type))'
	.' / SUM(t1.task_duration * IF(t1.task_duration_type = 24, '.$working_hours.', t1.task_duration_type))'
	.' AS project_percent_complete ');
$q->addJoin('companies', 'com', 'company_id = project_company');
$q->addJoin('tasks', 't1', 'projects.project_id = t1.task_project');
$q->addWhere($where_list.(($where_list)?' AND ':'').'t1.task_id = t1.task_parent' );
$q->addGroup('project_id');
$q->addOrder('project_name');
$psql = $q->prepare();
$q->clear();


$q->addTable('projects');
$q->addQuery('project_id, COUNT(t1.task_id) AS total_tasks, project_owner');
$q->addJoin('tasks', 't1', 'projects.project_id = t1.task_project');
if($where_list) {
	$q->addWhere($where_list);
}
$q->addGroup('project_id');
$psql2 = $q->prepare();
$q->clear();


$perms =& $AppUI->acl();
$projects = array();
$canViewTask = $perms->checkModule('tasks', 'view');
if ($canViewTask) {

	$prc = db_exec($psql);
	echo db_error();
	while ($row = db_fetch_assoc($prc)) {
		$projects[$row['project_id']] = $row;
	}

	$prc2 = db_exec($psql2);
	echo db_error();
	while ($row2 = db_fetch_assoc($prc2)) {
		if ($projects[$row2['project_id']]) {
			array_push($projects[$row2['project_id']], $row2);
		}
	}
}

$join = '';
// Pull tasks
$select = 'distinct tasks.task_id, task_parent, task_name, task_start_date, task_end_date, task_dynamic, task_pinned, '
	.'pin.user_id as pin_user, task_priority, task_percent_complete, task_duration, task_duration_type, task_project, '
	.'task_description, task_owner, task_status, usernames.user_username, usernames.user_id, task_milestone, '
	.'assignees.user_username as assignee_username, count(distinct assignees.user_id) as assignee_count, '
	.'co.contact_first_name, co.contact_last_name, count(distinct files.file_task) as file_count, tlog.task_log_problem';
$from = 'tasks';
$mods = $AppUI->getActiveModules();
if (!empty($mods['history']) && !getDenyRead('history')) {
	$select .= ', MAX(history_date) as last_update';
	$join = 'LEFT JOIN history ON history_item = tasks.task_id AND history_table="tasks" ';
}
$join .= 'LEFT JOIN projects ON project_id = task_project';
$join .= ' LEFT JOIN users as usernames ON task_owner = usernames.user_id';
// Show assignee and count
$join .= ' LEFT JOIN user_tasks as ut ON ut.task_id = tasks.task_id';
$join .= ' LEFT JOIN users as assignees ON assignees.user_id = ut.user_id';
$join .= ' LEFT JOIN contacts as co ON co.contact_id = usernames.user_contact';

// Check if there is log report with the problem flag enabled for the task
$join .= ' LEFT JOIN task_log AS tlog ON tlog.task_log_task = tasks.task_id AND tlog.task_log_problem > 0';

// Figure out if a file is attached to task
$join .= ' LEFT JOIN files on tasks.task_id = files.file_task';
$join .= ' LEFT JOIN user_task_pin as pin ON tasks.task_id = pin.task_id AND pin.user_id = ';
$join .= $user_id ? $user_id : $AppUI->user_id;

$where = $project_id ? ' task_project = '.$project_id : 'project_status <> 7';

if ($pinned_only) {
	$where .= ' AND task_pinned = 1 ';
}

switch ($f) {
case 'all':
	break;
case 'myfinished7days':
	$where .= ' AND user_tasks.user_id = '.$user_id;
case 'allfinished7days':
	$from = 'user_tasks, '.$from;
	$where .= ' AND task_project = projects.project_id AND user_tasks.task_id = tasks.task_id '
		.'AND task_percent_complete = 100 '
		.'AND task_end_date >= "'.date('Y-m-d 00:00:00', mktime(0, 0, 0, date('m'), date('d')-7, date('Y'))).'"';
	break;
case 'children':
	// patch 2.13.04 2, fixed ambigious task_id
	$where .= ' AND task_parent = '.$task_id.' AND tasks.task_id <> '.$task_id;
	break;
case 'myproj':
	$where .= ' AND project_owner = '.$user_id;
	break;
case 'mycomp':
	if(!$AppUI->user_company){
		$AppUI->user_company = 0;
	}
	$where .= ' AND project_company = '.$AppUI->user_company;
	break;
case 'myunfinished':
	$from = 'user_tasks, '.$from;
	// This filter checks all tasks that are not already in 100%
	// and the project is not on hold nor completed
	// patch 2.12.04 finish date required to be consider finish
	$where .= ' AND task_project = projects.project_id AND user_tasks.user_id = '.$user_id
		. ' AND user_tasks.task_id = tasks.task_id AND (task_percent_complete < 100 OR task_end_date = "")'
		. ' AND projects.project_status <> 7 AND projects.project_status <> 4 AND projects.project_status <> 5';
	break;
case 'allunfinished':
	// patch 2.12.04 finish date required to be consider finish
	// patch 2.12.04 2, also show unassigned tasks
	$where .= ' AND task_project = projects.project_id AND (task_percent_complete < 100 OR task_end_date = "")'
		. ' AND projects.project_status <> 7 AND projects.project_status <> 4 AND projects.project_status <> 5';
	break;
case 'unassigned':
	$join .= ' LEFT JOIN user_tasks ON tasks.task_id = user_tasks.task_id';
	$where .= ' AND user_tasks.task_id IS NULL';
	break;
case 'taskcreated':
	$where .= ' AND task_owner = '.$user_id;
	break;
default:
	$from = 'user_tasks, '.$from;
	$where .= ' AND task_project = projects.project_id AND user_tasks.user_id = '.$user_id
		. ' AND user_tasks.task_id = tasks.task_id';
	break;
}

if ($project_id && $showIncomplete) {
	$where .= ' AND ( task_percent_complete < 100 or task_percent_complete is null )';
}

$task_status = 0;
if ( $min_view ) {
	$task_status = isset($_REQUEST['show_task_options']) ?
		intval( dPgetParam( $_REQUEST, 'task_status', 0) ) :
		$AppUI->getState('TaskListShowInactive', 0);
	$AppUI->setState('TaskListShowInactive', $task_status);
}

$where .= ' AND task_status = '.$task_status;

// patch 2.12.04 text search
if ( $search_text = $AppUI->getState('searchtext') ) {
	$where .= " AND (task_name LIKE ('%$search_text%') OR task_description LIKE ('%$search_text%') )";
}

// filter tasks considering task and project permissions
$projects_filter = '';
$tasks_filter = '';

// TODO: Enable tasks filtering

$allowedProjects = $project->getAllowedSQL($AppUI->user_id, 'task_project');
if (count($allowedProjects)) {
	$where .= ' AND ' . implode(' AND ', $allowedProjects);
}

//
$obj =& new CTask;
$allowedTasks = $obj->getAllowedSQL($AppUI->user_id, 'tasks.task_id');
if ( count($allowedTasks)) {
	$where .= ' AND ' . implode(' AND ', $allowedTasks);
}

// Filter by company
if ( ! $min_view && $f2 != 'all' ) {
	$join .= ' LEFT JOIN companies ON company_id = projects.project_company';
	$where .= ' AND company_id = ' . intval($f2) . ' ';
}

// patch 2.12.04 ADD GROUP BY clause for assignee count
$tsql = "SELECT $select FROM ( $from ) $join WHERE $where GROUP BY task_id ORDER BY project_id, task_start_date";

if ($canViewTask) {
	$ptrc = db_exec( $tsql );
	if($ptrc != false) {
		$nums = db_num_rows( $ptrc );
	}
	echo db_error();
}
else {
	$nums = 0;
}

//pull the tasks into an array
for ($x=0; $x < $nums; $x++) {
	$row = db_fetch_assoc( $ptrc );

	//add information about assigned users into the page output
	$ausql = 'SELECT ut.user_id, u.user_username, contact_email, ut.perc_assignment, '
		.'SUM(ut.perc_assignment) AS assign_extent, contact_first_name, contact_last_name '
		.'FROM user_tasks ut LEFT JOIN users u ON u.user_id = ut.user_id LEFT JOIN contacts ON u.user_contact = contact_id '
		.'WHERE ut.task_id='.$row['task_id'].' GROUP BY ut.user_id';

	$paurc = db_exec( $ausql );
	$nnums = db_num_rows( $paurc );
	echo db_error();
	for ($xx=0; $xx < $nnums; $xx++) {
		$row['task_assigned_users'][] = db_fetch_assoc($paurc);
	}
	//pull the final task row into array
	$projects[$row['task_project']]['tasks'][] = $row;
}

?>

<script type="text/JavaScript">
function pinTask(handler, id)
{
	var src = handler.src.substr(handler.src.lastIndexOf('/')+1);
	var op = src == 'gray.png' ? 1 : 0;

	ajax.send('index.php?m=tasks&a=pin&suppressHeaders=1&task_id='+id+'&op='+op, '',
		function(r) {
			if (r != 'OK') {
				alert(r);
				return;
			}
			handler.src = op ? 'images/green.png' : 'images/gray.png';
			handler.title = op ? 'Unpin task' : 'Pin task';
		}
	);
}
</script>

<?php if ($min_view && $project_id) { ?>
<form name='task_list_options' method='POST' action='<?=$query_string?>'>
<input type='hidden' name='show_task_options' value='1'>
<table width='100%' border='0' cellpadding='7' cellspacing='0' class="<?= $min_view ? 'infopanel' : 'subinfopanel'?>">
<tr>
	<td>
<?
$project->load($project_id);
if ($m == 'projects' && $project->canCreateTasks()){
	showButton('new task', '?m=tasks&a=simpleaddedit&task_project='.$project_id);
}
?>
	</td>
	<td align='right'>
	<table border="0" cellspacing="0" cellpadding="0">
	<tr>
		<td><?=$AppUI->_('Show tasks')?>:</td>
		<td>
			<input id="idShowIA" type='checkbox' name='task_status' value="-1" onclick="this.form.submit()"
				<?=($task_status == -1) ? 'checked="checked"' : ''?> />
		</td>
		<td><label for="idShowIA"><?=$AppUI->_('Inactive')?></label>&nbsp;</td>
		<td>
			<input id="idShowIC" type='checkbox' name='show_incomplete' onclick="this.form.submit()"
				<?=$showIncomplete ? 'checked="checked"' : ''?> />
		</td>
		<td><label for="idShowIC"><?=$AppUI->_('Incomplete')?></label>&nbsp;</td>
	</tr>
	</table>
	</td>
</tr>
</form>
</table>
<?php } ?>
<table width="100%" border="0" cellpadding="3" cellspacing="0" class="list">
<tr>
	<th width="10">&nbsp;</th>
	<!--th width="10"><img src="images/pinup.gif" title="Pin"></th-->
	<th width="10"><img src="images/time_log.gif" title="New Log"></th>
	<th width="20"><?=$AppUI->_('Work')?></th>
	<!--th align="center"><?=sort_by_item_title( 'P', 'task_priority', SORT_NUMERIC )?></th-->
	<th width="200"><?=sort_by_item_title( 'Task Name', 'task_name', SORT_STRING )?></th>
	<th nowrap="nowrap"><?=sort_by_item_title( 'Figure', 'task_figure', SORT_STRING )?></th>
	<th nowrap="nowrap"><?=$AppUI->_('Quotation')?></th>
	<th nowrap="nowrap"><?=sort_by_item_title( 'Amount', 'task_duration', SORT_NUMERIC )?></th>
	<th nowrap="nowrap"><?=sort_by_item_title( 'Start Date', 'task_start_date', SORT_NUMERIC )?></th>
	<th nowrap="nowrap" class="last"><?=sort_by_item_title( 'Finish Date', 'task_end_date', SORT_NUMERIC )?></th>
	<!--th nowrap="nowrap"><?=sort_by_item_title( 'Last Update', 'last_update', SORT_NUMERIC )?></th-->
</tr>
<?php

reset( $projects );

$total_tasks = 0;
foreach ($projects as $k => $p) {
	$tnums = count( @$p['tasks'] );
	// don't show project if it has no tasks
	// patch 2.12.04, show project if it is the only project in view
	if ($tnums > 0 || $project_id == $p['project_id']) {
		$total_tasks++;
		if (!$min_view) {
?>
<tr>
<td>
	<a href="index.php?m=tasks&f=<?=$f?>&project_id=<?=$project_id ? 0 : $k?>">
		<img src="images/icons/<?=$project_id ? 'expand.gif' : 'collapse.gif'?>"
			title="<?=$project_id ? $AppUI->_('show other projects') : $AppUI->_('show only this project')?>"/>
	</a>
	</td>
	<td colspan="11" nowrap="nowrap">
	<table width="100%" border="0" cellspacing="0" cellpadding="2">
	<tr>
		<td nowrap style="border: outset #eeeeee 1px;background-color:#<?=$p['project_color_identifier']?>">
			<a href="javascript:viewProject(<?=$k?>)"><b><?=$p['company_name'].' :: '.$p['project_name']?></b></a>
		</td>
		<td nowrap="nowrap" width="<?=101 - intval($p['project_percent_complete'])?>%" class="internal">&nbsp;
			<?=intval($p['project_percent_complete'])?>%
		</td>
	</tr>
	</table>
</td>
</tr>
<?php
		}
		global $done;
		$done = array();
		if ( $task_sort_item1 != '' ) {
			if ( $task_sort_item2 != '' && $task_sort_item1 != $task_sort_item2 )
				$p['tasks'] = array_csort($p['tasks'], $task_sort_item1, $task_sort_order1, $task_sort_type1
					, $task_sort_item2, $task_sort_order2, $task_sort_type2 );
			else $p['tasks'] = array_csort($p['tasks'], $task_sort_item1, $task_sort_order1, $task_sort_type1 );
		}
		else {
			/* we have to calculate the end_date via start_date+duration for
			 ** end='0000-00-00 00:00:00' if array_csort function is not used
			 ** as it is normally done in array_csort function in order to economise
			 ** cpu time as we have to go through the array there anyway
			 */
			for ($j=0; $j < count($p['tasks']); $j++) {
				if ( $p['tasks'][$j]['task_end_date'] == '0000-00-00 00:00:00' ) {
					$p['tasks'][$j]['task_end_date'] = calcEndByStartAndDuration($p['tasks'][$j]);
				}
			}
		}

		for ($i=0; $i < $tnums; $i++) {
			$t = $p['tasks'][$i];

			if ($t['task_parent'] == $t['task_id']) {
				$is_opened = $open_task_all || in_array($t['task_id'], $tasks_opened);
				showtask( $t, 0, $is_opened );
				if($is_opened || $t['task_dynamic'] == 0) {
					findchild( $p['tasks'], $t['task_id'] );
				}
			}
			if ($search_text
				&& (strpos($t['task_name'], $search_text) !== false
				|| strpos($t['task_description'], $search_text) !== false)) {
					showtask($t, 1, false);
				}
		}
		// check that any 'orphaned' user tasks are also display
		for ($i=0; $i < $tnums; $i++) {
			if ( !in_array( $p['tasks'][$i]['task_id'], $done ) ) {
				if($p['tasks'][$i]['task_dynamic'] && in_array( $p['tasks'][$i]['task_parent'], $tasks_closed)) {
					closeOpenedTask($p['tasks'][$i]['task_id']);
				}
				if(in_array($p['tasks'][$i]['task_parent'], $tasks_opened)){
					showtask( $p['tasks'][$i], 1, false);
				}
			}
		}

		if($tnums && $dPconfig['enable_gantt_charts'] && !$min_view) {
?>
<tr>
	<td colspan="11" align="right">
	<?
		if ($p['project_owner'] == $AppUI->user_id || $AppUI->user_type <= 5) {
			showButton($AppUI->_('Reports'), 'index.php?m=projects&a=reports&project_id='.$k);
		}
		showButton($AppUI->_('Gantt chart'), 'index.php?m=tasks&a=viewgantt&project_id='.$k);
	?>
	</td>
</tr>
</form>
<?php
		}
	}
}
$AppUI->setState('tasks_opened', $tasks_opened);

if ($total_tasks == 0) {
	showEmptySpanRow('second');
}
?>
</table>
<div id="idLegend" style="display: none">
<table>
<tr>
	<td class="colorCell" bgcolor="#ffffff"><img src="images/blank.gif" width="12" height="12"></td>
	<td><?=$AppUI->_('Future Task')?></td>
	<td>&nbsp; &nbsp;</td>
	<td class="colorCell" bgcolor="#e6eedd"><img src="images/blank.gif" width="12" height="12"></td>
	<td><?=$AppUI->_('Started and on time')?></td>
	<td>&nbsp; &nbsp;</td>
	<td class="colorCell" bgcolor="#ffeebb"><img src="images/blank.gif" width="12" height="12"></td>
	<td><?=$AppUI->_('Should have started')?></td>
	<td>&nbsp; &nbsp;</td>
	<td class="colorCell" bgcolor="#CC6666"><img src="images/blank.gif" width="12" height="12"></td>
	<td><?=$AppUI->_('Overdue')?></td>
	<td>&nbsp; &nbsp;</td>
	<td class="colorCell" bgcolor="#aaddaa"><img src="images/blank.gif" width="12" height="12"></td>
	<td><?=$AppUI->_('Done')?></td>
</tr>
</table>
</div>
